// service/service.go - 服务层
package service

import (
	"net/http"
	// "spam4lixiang/model"
	"strings"
	"sync"
	"time"

	"github.com/PuerkitoBio/goquery"
	"github.com/patrickmn/go-cache"
)

var (
	once sync.Once
	// configs map[string]model.CarConfig
	baseURL = "https://www.lixiang.com/configuration.html?carModel=L6"
)

// 添加全局缓存变量
var configCache = cache.New(5*time.Minute, 10*time.Minute)

// 初始化服务（加载配置或抓取数据）
func Init() {
	once.Do(func() {
		//	configs = make(map[string]model.CarConfig)
		go fetchData("L6")
		go fetchData("L6PRO")
	})
}

// 修改后的fetchData方法
func fetchData(model string) {
	url := baseURL + model
	_, err := fetchAndCacheDocument(url)
	if err != nil {
		return
	}

	// config := parseConfiguration(doc)
	// configs[model] = config
}

// 新增文档获取和缓存方法
func fetchAndCacheDocument(url string) (*goquery.Document, error) {
	if cached, found := configCache.Get(url); found {
		return cached.(*goquery.Document), nil
	}

	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	doc, err := goquery.NewDocumentFromReader(resp.Body)
	if err != nil {
		return nil, err
	}

	configCache.Set(url, doc, cache.DefaultExpiration)
	return doc, nil
}

// 新增配置解析方法
func parseConfiguration(doc *goquery.Document) model.CarConfig {
	config := model.CarConfig{}

	// 查找所有配置部分
	doc.Find(".configuration-part").Each(func(i int, part *goquery.Selection) {
		sectionName := cleanText(part.Find(".configuration-label").First().Text())

		// 构建配置项映射
		sectionData := make(map[string]string)
		part.Find(".configuration-row.normal").Each(func(j int, row *goquery.Selection) {
			key := cleanText(row.Find(".configuration-label").Text())
			value := cleanText(row.Find(".configuration-value").Text())
			sectionData[key] = value
		})

		// 将不同板块存入对应字段
		switch sectionName {
		case "基础参数":
			config.BasicParams = parseBasicParams(sectionData)
		case "电池参数":
			config.BatteryParams = parseBatteryParams(sectionData)
			// 可以继续添加其他板块...
		}
	})

	// 提取价格信息
	config.RetailPrice = cleanText(doc.Find(".topbar-price span").Text()) + "万元"
	return config
}

// 辅助函数：清理文本内容
func cleanText(s string) string {
	return strings.TrimSpace(strings.ReplaceAll(s, "\n", ""))
}

// 基础参数解析示例
func parseBasicParams(data map[string]string) model.BasicParams {
	return model.BasicParams{
		Dimensions:    data["长度"] + "×" + data["宽度"] + "×" + data["高度"],
		Wheelbase:     data["轴距"],
		Seating:       data["座位数"],
		SeatingLayout: data["座位布局"],
		Range:         data["CLTC综合工况续航里程"],
		DriveSystem:   data["驱动形式"],
		TotalPower:    data["动力系统总功率"],
		TotalTorque:   data["动力系统总扭矩"],
		Acceleration:  data["0-100km/h加速时间"],
		TopSpeed:      data["最高车速"],
	}
}

// 电池参数解析示例
func parseBatteryParams(data map[string]string) model.BatteryParams {
	return model.BatteryParams{
		Capacity:   data["动力电池"],
		Type:       data["电池类型"],
		ChargeTime: data["直流快充充电时间"],
		Warranty:   data["电池保修"],
	}
}

// 获取配置
func GetConfig(model string) (model.CarConfig, bool) {
	cfg, exists := configs[model]
	return cfg, exists
}
